<script setup>
import {onBeforeUnmount, reactive, ref, onMounted, onUnmounted} from "vue";
import {ElMessage} from "element-plus";
import axios from '../request.js';

const ws = ref(null);
const inputValue = ref('');

const username = ref('')
const managerName = ref('')
const managerStates = ref();
const userAvatar = ref("https://q7.itc.cn/q_70/images03/20240423/6d236fae5c8f44ed9b60d977f32debb7.jpeg")
const adminAvatar = ref("https://q5.itc.cn/q_70/images03/20240409/2013315961114923a8c53c8b21b30bda.jpeg")

const messages = ref([]);
const historicalMessages = ref([])

const inputUsername = ref('');

const isShow = ref(false);
const isShow1 = ref(false);

onMounted(() => {
  getStatus();
})

//通过前台的getManagerStatusByManagerName接口拿到当前管理员的managerName
const getStatus = () => {
  axios.get("/customerService/getManagerStatusByManagerName").then(resp => {
    managerName.value = resp.message;
  })
}

// 建立 WebSocket 连接的函数
const connectWebSocket = (managerName) => {

  const wsUrl = `ws://localhost:8090/imserver/${managerName}`; // 替换为你的 WebSocket 服务器 URL

  // 创建 WebSocket 连接
  ws.value = new WebSocket(wsUrl);

  // WebSocket 事件监听器
  ws.value.onopen = () => {
    console.log('WebSocket 连接已建立');
  };

  ws.value.onmessage = handleMessage;

  ws.value.onerror = handleError1;

  ws.value.onclose = handleClose;
};

//管理员上线
const onLine = (managerName) => {
  axios.put("/customerService/updateOnByManagerName", null, {
    params: {managerName: managerName}
  }).then(resp => {
    // 如果上线成功，则设置对应管理员的状态为在线
    if (resp === true) {
      managerStates.value = true;
    }
  })
  connectWebSocket(managerName);
};

//管理员下线
const offLine = (managerName) => {
  axios.put("/customerService/updateOffByManagerName", null, {
    params: {managerName: managerName}
  }).then(resp => {
    // 如果下线成功，则设置对应管理员的状态为离线
    if (resp === true) {
      managerStates.value = false;
    }
  })
  ws.value.close();
};

const notifyUser = (username) => {
  const msg = JSON.stringify({type: 'notifyUser', userName: username, from: managerName.value});
  sendMessageToServer(msg);
};

// 处理收到的消息的函数
const handleMessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.type === 'notifyManager') {
    alert(`${msg.from} 请求与您聊天`)
    username.value = msg.from;
    notifyUser(username.value);
  }
  else if (msg.type === 'chat') {
    // 处理聊天消息
    if (msg.text === 'empty') {
      ElMessage({
        message: '服务端收到的问题为空',
        type: 'error',
      });
      return;
    }
    messages.value.push(msg);
    // 收到的消息
    console.log('收到消息:', messages);
  }
};

// 处理错误的函数
const handleError1 = (error) => {
  console.error('WebSocket 错误:', error);
};

// 处理连接关闭的函数
const handleClose = () => {
  console.log('WebSocket 连接已关闭');
};

// 构建和准备消息的内容
const prepareMessage = () => {
  if (!inputValue.value.trim()) {
    ElMessage({
      message: '请输入回答的相关内容',
      type: 'warning',
    });
    return;
  }
  const msg = JSON.stringify({type: 'chat', text: inputValue.value, from: managerName.value, to: username.value});
  sendMessageToServer(msg);
  inputValue.value = ''; // 清空输入框内容
};


// 向 WebSocket 服务器发送消息的函数
const sendMessageToServer = (message) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(message);
  } else {
    console.error('WebSocket 连接未建立');
  }
};

// 在组件卸载时断开 WebSocket 连接的钩子
onBeforeUnmount(() => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.close();
  }
});

//获取历史聊天记录
const getHistoricalMessages = (managerName, inputUsername) => {
  isShow.value = false;
  isShow1.value = true;
  axios.get("/customerService/getMessagesByUserNames", {
    params: {fromUserName: managerName, toUserName: inputUsername}
  }).then(resp => {
    if (resp.length <= 0) {
      ElMessage({
        title: 'Warning',
        message: `没有与用户${inputUsername}的聊天记录`,
        type: 'warning',
      });
    } else {
      historicalMessages.value = resp;
      console.log(historicalMessages.value)
      console.log(resp)
    }
  })
}
</script>

<template>
  <el-header style="font-size: 20px">网咖客户咨询中心</el-header>
  <div class="body">

    <div class="chat">
      <div class="header">问答区</div>
      <div class="managerInfo">
        {{ managerName }}
        <span v-if="managerStates">在线</span>
        <span v-else>离线</span>
        <button @click="onLine(managerName)">上线</button>
        <button @click="offLine(managerName)">下线</button>
      </div>
      <!--展示聊天-->
      <div class="chat-body">
        <div v-for="(msg, index) in messages" :key="index"
             :class="msg.from === username ? 'chat-right' : 'chat-left'">
          <div class="userInfo">
            <span class="username">{{ msg.from }}</span>
            <img :src="msg.from === username ? userAvatar : adminAvatar" class="avatar"/>
          </div>
          <p class="message-text">{{ msg.text }}</p>
        </div>
      </div>
      <div class="input-button">
        <input v-model="inputValue" placeholder="输入消息"/>
        <button @click="prepareMessage">发送消息</button>
      </div>
    </div>

    <!--聊天历史-->
    <div class="chatHistory">
      <div class="header">
        <span class="getHistoricalMessages" @click="isShow=true">查询聊天历史</span><br>
        <el-dialog v-model="isShow" title="获取聊天历史" width="500" :before-close="handleClose">
          <span>请输入用户名</span>
          <input v-model="inputUsername"/>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="isShow = false">取消</el-button>
              <el-button type="primary" @click="getHistoricalMessages(managerName,inputUsername)">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>

      <div class="chatHistory-body">
        <div v-if="isShow1">
          <div v-for="(msg, index) in historicalMessages" :key="index"
               :class="msg.fromUserName === inputUsername ? 'chat-right' : 'chat-left'">
            <div class="userInfo">
              <span class="username">{{ msg.fromUserName }}</span>
              <img :src="msg.fromUserName === inputUsername ? userAvatar : adminAvatar" class="avatar"/>
            </div>
            <div class="message-text">
            <p class="time">{{msg.addTime}}</p>
            <p>{{ msg.messagesText }}</p>
            </div>
          </div>
        </div>
      </div>
      <span @click="isShow1=true">展开</span>
      <span @click="isShow1=false">关闭</span>
    </div>

  </div>
</template>


<style scoped>
.body{
  display: flex;
  height: 580px;
}

.chat {
  text-align: center;
  border: 1px solid #b61b1b;
  width: 600px;

}

.chat-body {
  height: 420px;
  overflow: auto;
}

.chatHistory {
  margin-left: 1px;
  text-align: center;
  border: 1px solid #b61b1b;
  width: 600px;
}

.chatHistory-body {
  height: 500px;
  overflow: auto;
}

.chatHistory span {
  font-size: 18px;
  cursor: pointer;
  margin-left: 10px;
}

.header {
  background-color: #409EFF;
  color: white;
  text-align: center;
  padding: 10px 0;
  font-size: 18px;
}

.managerInfo {
  border-bottom: 1px solid #b61b1b;
  font-size: 20px;
  margin: 20px 0;
}

.managerInfo span {
  margin: 0 20px;

}

.managerInfo button {
  font-size: 18px;
  margin-right: 20px;
}

.chat-right {
  display: flex;
  flex-direction: row-reverse;
  margin: 10px 0;
}

.chat-left {
  display: flex;
  justify-content: flex-start;
  margin: 10px 0;
}

.userInfo {
  display: flex;
  align-items: center;
}

.username {
  font-weight: bold;
  margin-right: 10px;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
}

.message-text {
  background-color: #f1f1f1;
  padding: 10px;
  border-radius: 5px;
  max-width: 60%;
  word-break: break-word;
}

.message-text p{
  margin: 4px 0 4px 0;
}

.time{
  font-size: 12px;
  margin: 2px 0 2px 0;
}

.getHistoricalMessages {
  cursor: pointer;
  margin-top: 10px;
}

.getHistoricalMessages:hover {
  color: #007bff;
}

.input-button {
  margin-bottom: 10px;
}

.input-button input {
  font-size: 20px;
}

.input-button button {
  font-size: 18px;
}
</style>